const express = require("express");
const mongoose = require("mongoose");
const JWT = require("jsonwebtoken");
const path = require("path");


// 连接数据库
mongoose.connect("mongodb://127.0.0.1:27017/app")
  .then(() => {
    console.log("数据库连接成功");
    // 启动服务器
    const app = express();



    app.use(function (req, res, next) {
      res.header("Access-Control-Allow-Origin", "*")
      // 处理复杂跨域中的预检请求
      // options 是get put post patch delete option 请求方式的集合
      // 后端设置了get  前端只能用options
      if (req.method == "OPTIONS") {
        res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        res.header("Access-Control-Allow-Methods", "PUT,POST,GET,PATCH,DELETE,OPTIONS");
        res.sendStatus(200);/*让options请求快速返回*/
      } else {
        next();
      }
    })


    app.use(express.static("./api"));

    // app.use((req, res) => {
    //   res.sendFile(path.resolve(__dirname, "./api/index.html"));
    // });

    // 使用中间件处理参数
    app.use(express.json());
    app.use(express.urlencoded());
    // app.use(express.text());

    // // 设置token白名单 不要验证token 
    // const whiteList = ['/api/auth/register', '/api/auth/login']

    // app.use('/api', (req, res, next) => {
    //   let url = req._parsedUrl.pathname;
    //   if (whiteList.includes(url)) {
    //     next();
    //     return
    //   }

    //   // 获取请求头中的token
    //   try {
    //     // 获取token
    //     const token = req.headers["authorization"].replace("Bearer ", ""); //没有token，有错误
    //     // 解析token
    //     req.userInfo = JWT.verify(token, "hello world"); //过期了，也会报错

    //     next()
    //   } catch (error) {
    //     //token过期了，需要重新登录
    //     res.status(400).json({ message: "请重新登录" });
    //   }

    // })

    // 注册登录
    const authRouter = require('./routers/auth');
    app.use('/api/auth', authRouter);

    // 上传发布接口
    const Update = require('./routers/Update')
    app.use("/api/update", Update);

    // 个人中心
    const Mine = require('./routers/Mine')
    app.use('/api/mine', Mine)

    // 菜谱
    const Recipe = require('./routers/recipe')
    app.use('/api/recipe', Recipe)

    // 收藏
    const Collect = require('./routers/Collect')
    app.use('/api/Collect', Collect)

    // 关注
    const Concern = require('./routers/concern')
    app.use('/api/concern', Concern)

    app.use((req, res) => {
      res.sendFile(path.resolve(__dirname, "./api/index.html"));
    });

    app.listen(8000, "192.168.70.7", () => {
      console.log("服务器启动成功....");
    });
  })
  .catch((error) => {
    console.log("数据库连接失败:", error);
  });
